package com.bsh.repository;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.bsh.mybatis.IRepository.AccountMapper;
import com.bsh.mybatis.model.Account;
import com.bsh.mybatis.model.User;
import com.bsh.utils.Pager;

@Repository
public class DaoAccount {
	@Resource
	SqlSessionTemplate session;

	@Resource
	JdbcTemplate jdbcTemplate;
	@Resource
	NamedParameterJdbcTemplate namedJdbcTemplate;
	
	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	DaoUser daoUser;

	AccountMapper getMapper() {
		return session.getMapper(AccountMapper.class);
	}

	public int deleteByPrimaryKey(Integer id) {
		int res = getMapper().deleteByPrimaryKey(id);
		return res;
	}

	public int insert(Account record) {
		getMapper().insert(record);
		return record.getId();
	}

	public int insertSelective(Account record) {
		getMapper().insertSelective(record);
		return record.getId();
	}

	public Account selectByPrimaryKey(Integer id) {
		Account row = getMapper().selectByPrimaryKey(id);
		return row;
	}

	public int updateByPrimaryKeySelective(Account record) {
		int res = getMapper().updateByPrimaryKeySelective(record);
		return res;
	}

	public int updateByPrimaryKey(Account record) {
		int res = getMapper().updateByPrimaryKey(record);
		return res;
	}
	
	/**
	 * 取得用户账户信息
	 * @return
	 */
	public Account getUserAccount(int userid){
		Account row = getMapper().getByUserId(userid);
		return row;
	}

	/**
	 * 加减现金,参数正负
	 * @return
	 */
	public Integer addMoney(int accountId,int userid,BigDecimal money){
		return getMapper().addMoney(accountId,userid,money);
	}
	
	/**
	 * 加减商币,参数正负
	 * @return
	 */
	public Integer addCloudMoney(int accountId,int userid,BigDecimal cloudMoney){
		return getMapper().addCloudMoney(accountId,userid,cloudMoney);
	}
	
	/**
	 * 加减股权,参数正负
	 * @return
	 */
	public Integer addCloudShares(int accountId,int userid,BigDecimal cloudShare){
		return getMapper().addCloudShares(accountId,userid,cloudShare);
	}
	/**
	 * 检查用户账户，如不存在则创建
	 * @return 返回 accountId
	 */
	public Integer initUserAcount(int userid, String ip){
		//如果存在，返回帐号id
		Account acc = this.getUserAccount(userid);
		if(acc!=null)
			return acc.getId();
		
		//如果不存在，创建空帐号，返回帐号id
		User user = daoUser.getUser(userid);
		if(user==null){
			System.out.println(String.format("初使化用户帐号失败：没有查询到用户,userid=%s",userid));
			return -1;
		}
		AccountMapper mapper =  getMapper();
		Account accNew=new Account();
		accNew.setUserid(userid);
		accNew.setMoney(BigDecimal.ZERO);
		accNew.setCloudMoney(BigDecimal.ZERO);
		accNew.setEnabled((byte)1);
		accNew.setCreateTime(new Date());
		accNew.setIp(ip);
		accNew.setPayPassword(user.getPassword());
		int res = mapper.insert(accNew);
		if(res>0){
		  return accNew.getId();
		}
		return -1;
	}
	
	public Integer initUserAcount(int userid){
		return initUserAcount(userid,null);	
	}
	

	public Integer editAccountPassword(int accountId,int userId,String newPassword){
		return getMapper().editAccountPassword(accountId,userId,newPassword);
	}
	
	/**
	 * 账户列表
	 */
	public List<Map<String,Object>> getPage(Pager pager,String where,String order) {				
		StringBuilder sb=new StringBuilder();
		MapSqlParameterSource ps = new MapSqlParameterSource();		
		sb.append("select u.*,(select name from user where id=u.pid) pname,a.money,a.cloud_money");
		sb.append(" from account a");
		sb.append(" join user u on u.id=a.userid");				
		if(!StringUtils.isEmpty(where)){
			sb.append(where);
		}
		Integer count= namedJdbcTemplate.queryForInt("select count(0) from ("+sb.toString()+")v",ps);

		StringBuilder sb2=new StringBuilder();
		MapSqlParameterSource ps2 = new MapSqlParameterSource();
		sb2.append(sb.toString());
		/*if(!StringUtils.isEmpty(where)){
			sb2.append(where);
		}*/
		sb2.append(" order by ");
		if(!StringUtils.isEmpty(order)){			
			sb2.append(order+",");
		}
		sb2.append(" u.id desc ");
		
		sb2.append(" limit :start,:size");		
		ps2.addValue("start", pager.getStart());
		ps2.addValue("size", pager.getPageSize());
		List<Map<String,Object>> list=namedJdbcTemplate.queryForList(sb2.toString(), ps2);

		pager.setRowCount(count);
		return list;
	}

	public List<Map<String, Object>> getAccountListExport(String where,String order) {
		StringBuilder sb=new StringBuilder();
		MapSqlParameterSource ps = new MapSqlParameterSource();		
		sb.append("select u.name,u.real_name,u.ip,case sex when 'M' then '男' when 'F' then '女'  end as sex ,");
		sb.append("u.mobile,a.money,a.cloud_money,");
		sb.append("case level when 'comm' then '普通会员' when 'vip' then 'VIP会员' when 'gold' then '金钻会员'  end as level ,");
		sb.append("case is_effect when '0' then '无效' when '1' then '有效' end as is_effect,");
		sb.append("case is_merchant when '0' then '否' when '1' then '是' end as is_merchant,");
		sb.append("(select name from user where id=u.pid) pname,u.create_time");
		sb.append(" from account a");
		sb.append(" join user u on u.id=a.userid");				
		if(!StringUtils.isEmpty(where)){
			sb.append(where);
		}
		sb.append(" order by ");
		if(!StringUtils.isEmpty(order)){			
			sb.append(order+",");
		}
		sb.append(" u.id desc ");
		
		MapSqlParameterSource ps2 = new MapSqlParameterSource();
		List<Map<String,Object>> list=namedJdbcTemplate.queryForList(sb.toString(),ps2);
		return list;
	}
	
}
